package org.hepeng.fabric.gateway.pool.spring.filter;

import org.hepeng.fabric.gateway.pool.FabricGatewayKeyHolder;
import org.hepeng.fabric.gateway.pool.GatewayKeyProvider;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author he peng
 * @date 2022/5/20
 */
public class FabricGatewayFilter extends OncePerRequestFilter {

    private final GatewayKeyProvider keyProvider;

    public FabricGatewayFilter(GatewayKeyProvider keyProvider) {
        this.keyProvider = keyProvider;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            FabricGatewayKeyHolder.set(keyProvider.getKey(request));
            filterChain.doFilter(request , response);
        } finally {
            FabricGatewayKeyHolder.remove();
        }
    }
}
